from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from .serializers import OrderPlaceSerializer, OrderCommitSerializer

from goods.models import SKU
from rest_framework.response import Response

class OrderPlaceView(GenericAPIView):
    """
    订单结算
    """
    serializer_class = OrderPlaceSerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取redis中需要结算的商品
        user = request.user
        redis_conn = get_redis_connection('cart')
        cart_dict = redis_conn.hgetall('cart_%s' % user.id)
        cart_selected_list = redis_conn.smembers('cart_selected_%s' % user.id)

        # 拼接数据
        sku_list = []
        for sku_id in cart_selected_list:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 获取序列化器
        serializer = self.get_serializer(data=sku_list, many=True)
        # 返回响应
        context = {
            'skus': serializer.data,
            'freight': ''
        }
        return Response(context)


class OrderCommitView(CreateAPIView):
    serializer_class = OrderCommitSerializer
    permission_classes = [IsAuthenticated]



